from rest_framework import serializers
from .models import Course, CourseReminder, Semester


class CourseSerializer(serializers.ModelSerializer):
    """课程序列化器"""
    weekday_display = serializers.CharField(source='get_weekday_display', read_only=True)

    class Meta:
        model = Course
        fields = '__all__'
        read_only_fields = ['user', 'created_at', 'updated_at']

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class CourseReminderSerializer(serializers.ModelSerializer):
    """课程提醒序列化器"""
    course_name = serializers.CharField(source='course.course_name', read_only=True)

    class Meta:
        model = CourseReminder
        fields = '__all__'
        read_only_fields = ['user', 'sent_at', 'created_at']


class SemesterSerializer(serializers.ModelSerializer):
    """学期序列化器"""
    course_count = serializers.SerializerMethodField()

    class Meta:
        model = Semester
        fields = '__all__'
        read_only_fields = ['user', 'created_at', 'updated_at']

    def get_course_count(self, obj):
        return Course.objects.filter(user=obj.user).count()

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        # 如果设置为当前学期，将其他学期设置为非当前
        if validated_data.get('is_current'):
            Semester.objects.filter(user=validated_data['user'], is_current=True).update(is_current=False)
        return super().create(validated_data)

    def update(self, instance, validated_data):
        if validated_data.get('is_current'):
            Semester.objects.filter(user=instance.user, is_current=True).exclude(id=instance.id).update(is_current=False)
        return super().update(instance, validated_data)


class ImportCourseSerializer(serializers.Serializer):
    """导入课程序列化器"""
    educational_account = serializers.CharField(required=True, help_text='教务系统账号')
    educational_password = serializers.CharField(required=True, help_text='教务系统密码', style={'input_type': 'password'})
    semester = serializers.CharField(required=False, help_text='学期')
